/**
 * $Id$
 * 
 * @author Noritaka Horio<holy.shared.design@gmail.com>
 * @copyright 2009 Noritaka Horio all rights resrved. 
 * @license The MIT License
 * @version $Revision$
 * @since
 */

var PDE = {};

PDE.Loader = new Class({

	Implements: [Events, Options],

	options: {
		"basePath": "../airapp/pde/",
		"pdeDirectory": "app:/airapp/pde/",
		/*
		onComplete $empty
		*/
	},

	initialize: function(options) {
		this.setOptions(options);
		this.images = new Array();
		this.code = "";
		this.result = null;
	},

	load: function(id) {
		var loadFile = id + "/" + id + ".pde";

		var code = this.loadPDE(loadFile);

		var images = code.match(/loadImage\(\"?.+\"\);/gi);
		if (images) { 
			var src = "";
			var loadImages = new Array();
			images.each(function(path) {
				path = path.replace(/loadImage\(\"/, "");
				path = path.replace(/\"\);/, "");

				src  = this.options.basePath + id + "/" + path;
				code = code.replace(path, src);

				loadImages.push([src,src]);
			}.bind(this));
			this.images = loadImages;
		};

		this.code = code;

		this.result = new Hash({
			"code": this.code,
			"images": this.images
		});
		this.fireEvent("complete", [this.result]);
		return this.result;
	},

	/**
	 * @private
	 */
	loadPDE: function(path) {
		var f	= new air.File(this.options.pdeDirectory + "/" +path);
	    var fs	= new air.FileStream();
		try {
			fs.open(f, air.FileMode.READ);
			var content = fs.readUTFBytes(fs.bytesAvailable);
			fs.close();
		} catch (error) {
			air.trace("Failed:", f.nativePath)
			air.trace("Failed:", error.message)
		}
		return content;
	}

});




PDE.ContextLoader = new Class({

	Implements: [Events, Options],

	options: {
		"basePath": "../airapp/pde/",
		"pdeDirectory": "app:/airapp/pde/",
		/* onStart
		 * onLoad
		 * onProgress
		 */
	},

	initialize: function(options) {
		this.setOptions(options);
		this.context = null;
	},

	load: function() {
		this.fireEvent("start");

		var pdeContext = {};
		var pdeDirectory = new air.File(this.options.pdeDirectory);
		try {
			var loadCount = 1;
			var list = pdeDirectory.getDirectoryListing();
			for (var i = 0; l = list.length, i < l; i++) {
				var name = list[i].url;
				name = name.replace(this.options.pdeDirectory, "");
				if (name != ".svn") {
					var pde ={
						"name": name.replace("/", ""),
						"nativePath": list[i].nativePath,
						"url": list[i].url
					};
					pdeContext[list[i].name] = pde;
					this.fireEvent("progress", [loadCount, pde]);
					loadCount++;
				}
			}
		} catch (error) {
			air.trace("Failed:", error.message)
		}
		this.context = new Hash(pdeContext);

		this.fireEvent("complete", [this.context]);
		return this.context;
	}
});